{% extends "base.tmpl" %}
{% block title %} Mozilla Labs : TogetherJS app integration example {% endblock %}
{# set enableExample true #}
{% block body %}

<div class="container">
  <section class="body-content row" id="main-section" data-speed="4" data-type="background">

<h1>Identity/Persona Example</h1>

<p>TogetherJS will pick up your login information (and gravatar):
<button id="login"><img src="https://developer.mozilla.org/files/3969/plain_sign_in_blue.png"></button>
<button id="logout" style="display: none">logout</button>
<button onclick="TogetherJS(this); return false">Collaborate</button>
</p>

<div>
The integration code:<br>
<pre id="main-code-dest">
</pre>

<!--
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
   <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" />
</svg>
-->

</div>

    <script src="https://login.persona.org/include.js"></script>
    <script src="./md5.js"></script>
    <script id="main-code">
var USER;
$(function () {
  $("#main-code-dest").text($("#main-code").text());

  $("#login").click(function () {
    navigator.id.request();
  });
  $("#logout").click(function () {
    navigator.id.logout();
  });

  navigator.id.watch({
    onlogin: function (assertion) {
      assertion = assertion.replace(/-/g, "+");
      assertion = assertion.replace(/_/g, "/");
      var parts = assertion.split(/\./g);
      var data = JSON.parse(atob(parts[1]));
      USER = data.principal.email;
      $("#logout").text("Logged in: " + USER);
      $("#login").hide();
      $("#logout").show();
      TogetherJS.refreshUserData();
    },
    onlogout: function () {
      USER = null;
      $("#login").show();
      $("#logout").hide();
      if (TogetherJS.require) {
        TogetherJS.require("session").close();
      }
    }
  });
});

function gravatar(email, options) {
  options = options || "";
  email = email.toLowerCase().replace(/^\s+/, "").replace(/\s+$/, "");
  var md5 = CryptoJS.MD5(email);
  return "https://www.gravatar.com/avatar/" + md5 + options;
}

TogetherJS.config("getUserName", function () {
  return USER;
});

TogetherJS.config("getUserAvatar", function () {
  if (! USER) {
    return null;
  }
  console.log("avatar", gravatar(USER, "?s=40&d=retro"));
  return gravatar(USER, "?s=40&d=retro");
});

    </script>

  </section>

</div><!-- /.container -->

{% endblock %}
